package com.zhenwgang.listen_books.servlet.album;

import com.zhenwgang.listen_books.repository.AlbumRepo;
import com.zhenwgang.listen_books.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Violet
 * @date 2022/07/16 11:55
 **/
@WebServlet("/studio/album/withdraw.do")
public class WithdrawDOServlet extends HttpServlet {
    private final AlbumRepo albumRepo = new AlbumRepo();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null){
            throw new RuntimeException("用户未登录");
        }

        UserVO currentUser = (UserVO) session.getAttribute("currentUser");
        if (currentUser == null){
            throw new RuntimeException("用户未登录");
        }

        int aid = Integer.parseInt(req.getParameter("aid"));
        Integer uid = albumRepo.selectUidByAid(aid);
        if (uid == null || !uid.equals(currentUser.uid)){
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/plain");
            PrintWriter writer = resp.getWriter();
            writer.println("此专辑不属于该用户");
        }

        albumRepo.updateWithdraw(aid);
        resp.sendRedirect("/studio/album/list.html");
    }
}